import React, { useEffect, useState,useCallback } from 'react'
import {message} from 'antd'
import {MAX_RILE_SIZE} from './constant'
function useDrag(uploadContainerRef) {
    //定义一个状态用来保存用户选中的文件
    const [selectedFile,setselectedFile] = useState(null)
    //存放文件的预览信息url是预览的地址，type是文件的类型
    const [filePreview,setfilePreview] = useState({url:null,type:null})
    const handleDrag = useCallback((event)=>{
        event.preventDefault();//阻止默认行为
        event.stopPropagation();//阻止事件传播
    },[])
    const checkFile = (files)=>{
        const file = files[0]
        console.log(file);
        
        if(!file){
            message.error('没有选择任何文件')
        }
        //判断文件大小
        if(file.size > MAX_RILE_SIZE){
            console.log('文件大小不能超过2G');
            return
        }
        //判断类型
        if(!(file.type.startsWith('image/') || file.type.startsWith('video/'))){
            console.log('只能传输图片或视频');
            return 
        }
        setselectedFile(file)
    }
    const handleDrop = useCallback((event)=>{
        event.preventDefault();//阻止默认行为
        event.stopPropagation();//阻止事件传播
        checkFile(event.dataTransfer.files)
        // const {files} = event.dataTransfer;
    },[])
    useEffect(()=>{
        const uploadContainer = uploadContainerRef.current;
        uploadContainer.addEventListener('dragenter',handleDrag);
        uploadContainer.addEventListener('dragover',handleDrag);
        uploadContainer.addEventListener('drop',handleDrop);
        uploadContainer.addEventListener('dragleave',handleDrag);
        return ()=>{
            uploadContainer.addEventListener('dragenter',handleDrag);
            uploadContainer.addEventListener('dragover',handleDrag);
            uploadContainer.addEventListener('drop',handleDrop);
            uploadContainer.addEventListener('dragleave',handleDrag);
        }
    },[])
    useEffect(()=>{
        if(!selectedFile)return;
        const url = URL.createObjectURL(selectedFile)
        setfilePreview({url,type:selectedFile.type})
        //useEffect会返回一个销毁函数
        return ()=>{//revokeObjectURL可以撤销此占用的资源
            URL.revokeObjectURL(url)
        }
    },[selectedFile]);
    const resetFileStatus = ()=>{
        setselectedFile(null)
        setfilePreview({url:null,type:null})
    }
  return {selectedFile,filePreview,resetFileStatus}
}
export default useDrag
